//
//  GPSManager.m
//  YanXiuWang
//
//  Created by 慧趣小歪 on 17/1/7.
//  Copyright © 2017年 小分队. All rights reserved.
//

#import "GPSManager.h"

@interface GPSManager () {
    CLLocationManager *_locationManager;
    NSMutableArray *_callbacks;
}

@end

@implementation GPSManager

- (void)getLocationOnComplete:(GPS_MANAGER_COMPLETE)onComplete {
    if (onComplete == nil) return;
    if (_callbacks == nil) {
        _callbacks = [NSMutableArray arrayWithCapacity:1];
    }
    
    [_callbacks addObject:[onComplete copy]];
    
    if (_locationManager == nil) {
        // 初始化定位管理器
        _locationManager = [[CLLocationManager alloc] init];
        // 设置代理
        _locationManager.delegate = self;
        // 设置定位精确度到米
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 设置过滤器为无
        _locationManager.distanceFilter = 1000;
        // 开始定位
        [_locationManager requestWhenInUseAuthorization];
        
        [_locationManager startUpdatingLocation];
    }
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    for (GPS_MANAGER_COMPLETE callback in _callbacks) {
        callback(locations.firstObject);
    }
    _callbacks = nil;
    [_locationManager stopUpdatingLocation];
    _locationManager = nil;
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
    for (GPS_MANAGER_COMPLETE callback in _callbacks) {
        callback(nil);
    }
    _callbacks = nil;
    [_locationManager stopUpdatingLocation];
    _locationManager = nil;
}

@end

#pragma mark - 单例相关
static dispatch_once_t onceToken;
static GPSManager *instance;
@implementation GPSManager (Once)

+ (nonnull instancetype)shared {
    return [GPSManager new];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

- (instancetype)init {
    dispatch_once(&onceToken, ^{
        instance = [super init];
    });
    self = instance;
    return self;
}

- (id)copy {
    return self;
}

- (id)mutableCopy {
    return self;
}

@end
